import { Effect } from 'dva';
import { Reducer } from 'redux';

import Cookies from 'js-cookie';
import {
  queryCurrent,
  logout,
} from '@/services/user';
import { domain } from '../../config/request.config';
import { loginPath } from '../../config/request.config';

export interface CurrentUser {
  avatar?: string;
  name?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  unreadCount?: number;
}

export interface UserModelState {
  currentUser?: CurrentUser;
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface UserModelType {
  namespace: string;
  state: UserModelState;
  effects: {
    logout: Effect;
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    cleanUser: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    * logout({ payload }, { put, call }) {
      // clean
      const response = yield call(logout);
      if (response.code === 0) {
        Cookies.remove('session_id', { domain });
        window.location.href = loginPath;
      }
    },

    // 查询当前用户
    * fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response.body,
      });
      // } else {
      //   yield put({
      //     type: 'logout',
      //   });
      // }
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },

    cleanUser() {
      return {};
    },

  },
};

export default UserModel;
